package com.example.casper.Experiment2024;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

//import androidx.appcompat.app.AlertDialog;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.casper.Experiment2024.data.BookItem;
import com.example.casper.Experiment2024.data.DataBank;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class Hello1826Activity extends AppCompatActivity {
    private String[] tabHeaderStrings={"Items","News","Map"};

    /*
        private ArrayList<BookItem> items;
        ActivityResultLauncher<Intent> addItemLauncher;
        ActivityResultLauncher<Intent> updateItemLauncher;
        private BookItemAdapter b=new BookItemAdapter(items);;


        @Override
        public boolean onContextItemSelected(MenuItem item) {

            switch (item.getItemId()) {
                case 0:
                    Intent intent = new Intent(Hello1826Activity.this, BookItemDetailActivity.class);
                    addItemLauncher.launch(intent);
                    break;
                case 1:
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Delete Data");
                    builder.setMessage("Are you sure you want to delete this data?");
                    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            items.remove(item.getOrder());
                            b.notifyItemRemoved(item.getOrder());
                            b.notifyDataSetChanged();
                            DataBank databank =new DataBank(Hello1826Activity.this);
                            databank.SaveBookItems(items);

                        }
                    });
                    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                    break;
                case 2:
                    Intent intentUpdate = new Intent(Hello1826Activity.this, BookItemDetailActivity.class);
                    BookItem shopItem= items.get(item.getOrder());
                    intentUpdate.putExtra("name",shopItem.getName());
                    intentUpdate.putExtra("price",shopItem.getPrice());
                    intentUpdate.putExtra("position",item.getOrder());
                    updateItemLauncher.launch(intentUpdate);
                    break;
                default:
                    return super.onContextItemSelected(item);
            }
            return true;
        }
        @SuppressLint("NotifyDataSetChanged")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            addItemLauncher = registerForActivityResult(
                    new ActivityResultContracts.StartActivityForResult(),
                    result -> {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            Intent data = result.getData();
                            assert data!=null;
                            String name = data.getStringExtra("name"); // 获取返回的数据
                            String priceText = data.getStringExtra("price"); // 获取返回的数据

                            double price= Double.parseDouble(priceText);
                            items.add(new BookItem(name, price, R.drawable.pic1));
                            b.notifyItemInserted(items.size()-1);
                            b.notifyDataSetChanged();
                            DataBank databank =new DataBank(Hello1826Activity.this);
                            databank.SaveBookItems(items);

                        } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                            // 处理取消操作
                        }
                    }
            );
            updateItemLauncher = registerForActivityResult(
                    new ActivityResultContracts.StartActivityForResult(),
                    result -> {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            Intent data = result.getData();
                            assert data !=null;
                            int position = data.getIntExtra("position",0);
                            String name = data.getStringExtra("name"); // 获取返回的数据
                            String priceText = data.getStringExtra("price"); // 获取返回的数据

                            double price= Double.parseDouble(priceText);
                            BookItem shopItem = items.get(position);
                            shopItem.setPrice(price);
                            shopItem.setName(name);
                            b.notifyItemChanged(position);
                            b.notifyDataSetChanged();
                            DataBank databank =new DataBank(Hello1826Activity.this);
                            databank.SaveBookItems(items);

                        } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                            // 处理取消操作
                        }
                    }
            );
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_hello1826);



            items = new ArrayList<>();
            DataBank databank =new DataBank(this);
            items = databank.readItems();
            if(items.isEmpty())
                items.add(new BookItem("信息安全数学基础（第2版）",1.0, R.drawable.pic3));
    //        items.add(new BookItem("创新工程实践",4.0, R.drawable.pic1));
    //        items.add(new BookItem("软件项目管理案例教程（第3版）",3.0, R.drawable.pic2));
    //        items.add(new BookItem("信息安全数学基础（第2版）",1.0, R.drawable.pic3));
            //for (int i = 0; i < 5; i++)
            //    items.add(new BookItem("信息安全数学基础（第2版）",1.0, R.drawable.pic3));
            /*for(int i=0;i<3;++i){

            }
            RecyclerView mainRecyclerView = findViewById(R.id.recycler_view_the_books);
            mainRecyclerView.setLayoutManager(new LinearLayoutManager(this));

            BookItemAdapter BookItemAdapter = new BookItemAdapter(items);
            mainRecyclerView.setAdapter(BookItemAdapter);

            registerForContextMenu(mainRecyclerView);

            ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
                Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
                return insets;
            });
        }

        private  class BookItemAdapter extends RecyclerView.Adapter {

            private final List<BookItem> items;

            public BookItemAdapter(List<BookItem> items) {
                this.items = items;
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.recycle_1826, parent, false);
                return new MyViewHolder(view);
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                MyViewHolder myViewHolder = (MyViewHolder) holder;
                myViewHolder.getTextViewName().setText(items.get(position).getName());
                //myViewHolder.getTextViewPrice().setText(""+items.get(position).getPrice());
                myViewHolder.getImageViewPicture().setImageResource(items.get(position).getImageResourceId());

            }

            @Override
            public int getItemCount() {
                return items.size();
            }
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            public ImageView getImageViewPicture() {
                return imageViewPicture;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewPrice() {
                return textViewPrice;
            }

            private final ImageView imageViewPicture;

            private final TextView textViewName;

            private final TextView textViewPrice;

            //private final TextView textViewPrice;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                this.imageViewPicture = itemView.findViewById(R.id.image_view_book_cover);
                this.textViewName = itemView.findViewById(R.id.textview_item_name);
                this.textViewPrice = itemView.findViewById(R.id.textview_item_price);

                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");

                menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
                menu.add(0, 1, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
                menu.add(0, 2, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
            }
        }
        */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello1826);
        // 获取ViewPager2和TabLayout的实例
        ViewPager2 viewPager = findViewById(R.id.view_pager);
        TabLayout tabLayout = findViewById(R.id.tab_layout);
        // 创建适配器
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), getLifecycle());
        viewPager.setAdapter(fragmentAdapter);


        // 将TabLayout和ViewPager2进行关联
        new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> tab.setText(tabHeaderStrings[position])
        ).attach();
    }
    public class FragmentAdapter extends FragmentStateAdapter {
        private static final int NUM_TABS = 3;
        public FragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            // 根据位置返回对应的Fragment实例
            switch (position) {
                case 0:
                    return ShoppingListFragment.newInstance();
                case 1:
                    return WebViewFragment.newInstance("http://news.sina.com.cn");
                case 2:
                    return new TencentMapFragment();
                default:
                    return new ShoppingListFragment();
            }
        }

        @Override
        public int getItemCount() {
            return NUM_TABS;
        }
    }
}